package net.courier.remoting.provider.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundMessageHandlerAdapter;
import net.courier.remoting.ServiceRegistry;
import net.courier.remoting.protocol.RequestDatagram;
import net.courier.remoting.protocol.ResponseDatagram;
import net.courier.remoting.server.MethodInvokeHelper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MethodInvokeHandler extends ChannelInboundMessageHandlerAdapter<RequestDatagram> {
	private static final Logger LOGGER = LoggerFactory.getLogger(MethodInvokeHandler.class);

	private final MethodInvokeHelper helper;

	public MethodInvokeHandler(ServiceRegistry registry) {
		this.helper = new MethodInvokeHelper(registry);
	}

	@Override
	public void messageReceived(ChannelHandlerContext ctx, RequestDatagram msg) throws Exception {
		Object result = helper.invoke(msg);

		ResponseDatagram datagram = new ResponseDatagram();
		datagram.setResult(result);

		ctx.write(datagram);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		LOGGER.warn("处理消息发生异常", cause);
		ctx.close();
	}
}
